//
//  ToastResultView.swift
//  TCToast
//
//  Created by 叮叮 on 2021/3/19.
//

import Foundation
import UIKit

enum ResultType {
    /// 结果为成功
    case success
    
    /// 结果为失败
    case fail
    
    /// 没有结果
    case none
}

class ToastResultView: UIView {
    
    /// 内容视图
    var contentView: UIView?
    
    /// 指示器
    var indicator: UIView?
    
    /// 显示文本
    var textLabel: UILabel?
    
    /// 结果类型
    var type: ResultType
    
    init(type: ResultType) {
        self.type = type
        super.init(frame: .zero)
        setContentView()
        setContentViewConstraint()
        setIndicatorLabelContentView()
    }
    
    /// 设置内容视图
    func setContentView() {
        contentView = UIView()
        contentView?.translatesAutoresizingMaskIntoConstraints = false
        contentView?.layer.cornerRadius = 15
        contentView?.layer.masksToBounds = true
        contentView?.layer.backgroundColor = UIColor.white.withAlphaComponent(0.5).cgColor
        addSubview(contentView!)
        
        var style = UIBlurEffect.Style.light
        if (TCToast.toastDisplayType == .dark) {
            style = UIBlurEffect.Style.dark
        }
        let blur = UIBlurEffect(style: style)
        let visual = UIVisualEffectView(effect: blur)
        visual.translatesAutoresizingMaskIntoConstraints = false
        contentView?.addSubview(visual)
        
        matchParentView(superView: contentView, subView: visual)
    }
    
    /// 设置内容视图约束
    func setContentViewConstraint() {
        matchParentView(superView: self, subView: contentView!)
    }
    
    /// 子视图等于父视图
    func matchParentView(superView: UIView?, subView: UIView) {
        
        guard let view = superView else { return }
        
        let topConstraint = NSLayoutConstraint(item: subView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)
        let bottomConstraint = NSLayoutConstraint(item: subView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
        let leftConstraint = NSLayoutConstraint(item: subView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0)
        let rightConstraint = NSLayoutConstraint(item: subView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0)

        view.addConstraint(topConstraint)
        view.addConstraint(bottomConstraint)
        view.addConstraint(leftConstraint)
        view.addConstraint(rightConstraint)
    }
    
    /// 设置加载指示器和文本内容视图
    func setIndicatorLabelContentView() {
        let mixedView = UIView()
        mixedView.translatesAutoresizingMaskIntoConstraints = false
        contentView?.addSubview(mixedView)
        
        if let indicator = setSuccessIndicator() {
            mixedView.addSubview(indicator)
            setIndicatorConstraint(superView: mixedView)
            indicator.layoutIfNeeded()
        }
        
        let textLabel = setLabel()
        mixedView.addSubview(textLabel)
        setLabelConstraint(superView: mixedView)
        
        guard let content = contentView else { return }
        
        let leftConstraint = NSLayoutConstraint(item: mixedView, attribute: .left, relatedBy: .greaterThanOrEqual, toItem: content, attribute: .left, multiplier: 1, constant: 0)
        let rightConstraint = NSLayoutConstraint(item: mixedView, attribute: .right, relatedBy: .lessThanOrEqual, toItem: content, attribute: .right, multiplier: 1, constant: 0)
        let centerYConstraint = NSLayoutConstraint(item: mixedView, attribute: .centerY, relatedBy: .equal, toItem: content, attribute: .centerY, multiplier: 1, constant: 0)
        let centerXConstraint = NSLayoutConstraint(item: mixedView, attribute: .centerX, relatedBy: .equal, toItem: content, attribute: .centerX, multiplier: 1, constant: 0)
        let topConstraint = NSLayoutConstraint(item: mixedView, attribute: .top, relatedBy: .lessThanOrEqual, toItem: content, attribute: .top, multiplier: 1, constant: 10)
        let bottomConstraint = NSLayoutConstraint(item: mixedView, attribute: .bottom, relatedBy: .lessThanOrEqual, toItem: content, attribute: .bottom, multiplier: 1, constant: -10)
        let heightConstraint = NSLayoutConstraint(item: mixedView, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: 80)

        content.addConstraint(leftConstraint)
        content.addConstraint(rightConstraint)
        content.addConstraint(centerYConstraint)
        content.addConstraint(centerXConstraint)
        content.addConstraint(topConstraint)
        content.addConstraint(bottomConstraint)
        content.addConstraint(heightConstraint)
    }
    
    /// 设置成功指示器
    func setSuccessIndicator() -> UIView? {
        if type == .success {
            indicator = SuccessIndicator()
        } else if type == .fail {
            indicator = FailureIndicator()
        }
        indicator?.translatesAutoresizingMaskIntoConstraints = false
        return indicator
    }
    
    /// 设置成功指示器约束
    func setIndicatorConstraint(superView: UIView) {
        
        guard let certainIndicator = indicator else { return }
        
        let topConstraint = NSLayoutConstraint(item: certainIndicator, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1, constant: 0)
        let leftConstraint = NSLayoutConstraint(item: certainIndicator, attribute: .left, relatedBy: .greaterThanOrEqual, toItem: superView, attribute: .left, multiplier: 1, constant: 0)
        let rightConstraint = NSLayoutConstraint(item: certainIndicator, attribute: .right, relatedBy: .lessThanOrEqual, toItem: superView, attribute: .right, multiplier: 1, constant: 0)
        let centerXConstraint = NSLayoutConstraint(item: certainIndicator, attribute: .centerX, relatedBy: .equal, toItem: superView, attribute: .centerX, multiplier: 1, constant: 0)
        let heightConstraint = NSLayoutConstraint(item: certainIndicator, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50)
        let widthConstraint = NSLayoutConstraint(item: certainIndicator, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 50)

        superView.addConstraint(topConstraint)
        superView.addConstraint(leftConstraint)
        superView.addConstraint(rightConstraint)
        superView.addConstraint(centerXConstraint)
        superView.addConstraint(heightConstraint)
        superView.addConstraint(widthConstraint)
    }
    
    /// 设置显示文本
    func setLabel() -> UILabel {
        textLabel = UILabel()
        textLabel?.translatesAutoresizingMaskIntoConstraints = false
        textLabel?.numberOfLines = 0
        textLabel?.text = "12314"
        if TCToast.toastDisplayType == .light {
            textLabel?.textColor = .black
        } else {
            textLabel?.textColor = .white
        }
        return textLabel!
    }
    
    /// 设置显示文本约束
    func setLabelConstraint(superView: UIView) {
        
        guard let label = textLabel else { return }
        
        let leftConstraint = NSLayoutConstraint(item: label, attribute: .left, relatedBy: .equal, toItem: superView, attribute: .left, multiplier: 1, constant: 10)
        let rightConstraint = NSLayoutConstraint(item: label, attribute: .right, relatedBy: .equal, toItem: superView, attribute: .right, multiplier: 1, constant: -10)
        
        var topConstraint: NSLayoutConstraint
        if let certainIndicator = indicator {
            topConstraint = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: certainIndicator, attribute: .bottom, multiplier: 1, constant: 0)
        } else {
            topConstraint = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1, constant: 0)
        }
        let bottomConstraint = NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: superView, attribute: .bottom, multiplier: 1, constant: 0)

        superView.addConstraint(leftConstraint)
        superView.addConstraint(rightConstraint)
        superView.addConstraint(topConstraint)
        superView.addConstraint(bottomConstraint)
    }
    
    /// 开始指示器动画
    func startAnimation() {
        if indicator is SuccessIndicator {
            let success = indicator as? SuccessIndicator
            success?.setSuccessIndicator()
        } else if indicator is FailureIndicator {
            let failure = indicator as? FailureIndicator
            failure?.setFailureIndicator()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class SuccessIndicator: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    /// 画成功指示器
    func setSuccessIndicator() {
        
        let width = bounds.size.width
        let height = bounds.size.height
        
        let shape = CAShapeLayer()
        shape.backgroundColor = UIColor.clear.cgColor
        shape.frame = bounds
        layer.addSublayer(shape)
        
        let bezier = UIBezierPath()
        bezier.move(to: CGPoint(x: width / 7, y: height / 2))
        bezier.addLine(to: CGPoint(x: width * 5 / 11, y: height * 3 / 4))
        bezier.addLine(to: CGPoint(x: width * 7 / 8, y: height / 6))
        shape.path = bezier.cgPath
        shape.fillColor = UIColor.clear.cgColor
        shape.lineWidth = 5
        shape.lineCap = .round
        shape.strokeColor = UIColor.systemGreen.cgColor
        shape.strokeEnd = 0
        
        
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.duration = TCToast.indicatorTime
        animation.toValue = 1
        animation.isRemovedOnCompletion = false
        animation.fillMode = .forwards
        shape.add(animation, forKey: "success")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class FailureIndicator: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    /// 画失败指示器
    func setFailureIndicator() {
        
        let width = bounds.size.width
        let height = bounds.size.height
        
        let shape = CAShapeLayer()
        shape.backgroundColor = UIColor.clear.cgColor
        shape.frame = bounds
        layer.addSublayer(shape)
        
        let bezier = UIBezierPath()
        bezier.move(to: CGPoint(x: width / 6, y: height / 6))
        bezier.addLine(to: CGPoint(x: width * 5 / 6, y: height * 5 / 6))
        
        bezier.move(to: CGPoint(x: width / 6, y: height * 5 / 6))
        bezier.addLine(to: CGPoint(x: width * 5 / 6, y: height / 6))
        shape.path = bezier.cgPath
        shape.fillColor = UIColor.clear.cgColor
        shape.lineWidth = 5
        shape.lineCap = .round
        shape.strokeColor = UIColor.systemRed.cgColor
        shape.strokeEnd = 0
        
        
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.duration = TCToast.indicatorTime
        animation.toValue = 1
        animation.isRemovedOnCompletion = false
        animation.fillMode = .forwards
        shape.add(animation, forKey: "success")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
